import { getToken, clearAll, setToken, setItem, getItem } from '@u/tool/storage'
import { login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { adminRoutes, ordinaryRoutes } from '@/router/temp-routes'

const state = {
  token: getToken(),
  id: '',
  name: '',
  avatar: '',
  roles: [],
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    console.log('登录的信息：', userInfo)
    return new Promise((resolve, reject) => {
      // userId 临时的，需要更改直接换userInfo
      login({ userId: '0' }).then(response => {
        const token = response || '000E67F9AF0C724BF08EAD710A9612C7'
        // 登录角色（临时的）
        setItem('role', userInfo.userName)
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo({ token: state.token }).then(response => {
        const { id, name = '', permissions = [], avatar } = response
        commit('SET_ID', id)
        commit('SET_NAME', name)
        commit('SET_ROLES', getItem('role') === 'admin' ? ['admin'] : ['ordinary'])
        commit('SET_PERMISSIONS', permissions)
        commit('SET_AVATAR', avatar || 'https://upload.jianshu.io/users/upload_avatars/16493824/9664ee7b-c040-4c3a-ab30-5a628e912046.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/72/h/72')
        resolve(getItem('role') === 'admin' ? adminRoutes : ordinaryRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出
  logout({ commit }) {
    return new Promise(resolve => {
      // 先删除令牌
      clearAll()
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      // 重置路由
      commit('permission/SET_ROUTES', [], { root: true })
      resetRouter()
      resolve()
    })
  },

  // 移除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // 必须先删除令牌
      clearAll()
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

